/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.storebits.testsystem;

import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Ventsi
 */
@ManagedBean(name = "authentication")
@RequestScoped
public class AuthenticationBean implements Serializable{

    private String username;
    private String password;

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public String getUsername() {
        return username;
    }

    public String login() {
        String result = "/index?faces-redirect=true";
        
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        try {
            request.login(this.username, this.password);

        } catch (ServletException e) {
            result = "/loginError?faces-redirect=true";
        }
        System.out.println(context.getExternalContext().isUserInRole("user"));
        System.out.println(context.getExternalContext().isUserInRole("admin"));
        return result;
    }

    public String logout() {
        String result = "/index?faces-redirect=true";

        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

        try {
            request.logout();
        } catch (ServletException e) {
            result = "/loginError?faces-redirect=true";
        }

        return result;
    }
}
